%%% Copyright 2010 Google Inc.
%%%
%%% Licensed under the Apache License, Version 2.0 (the "License");
%%% you may not use this file except in compliance with the License.
%%% You may obtain a copy of the License at
%%%
%%%     http://www.apache.org/licenses/LICENSE-2.0
%%%
%%% Unless required by applicable law or agreed to in writing, software
%%% distributed under the License is distributed on an "AS IS" BASIS,
%%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%%% See the License for the specific language governing permissions and
%%% limitations under the License.

%%% @copyright 2010 Google Inc. All Rights Reserved.
%%% @author <jacoby@google.com> Jacoby Thwaites [http://sites/madcloud]
%%% @version {@version}
%%% @doc Tests for node_srv module.
%%%
%%% Note that this deletes all Mnesia data on the test node.
%%%
-module(node_srv_tests).

%% Include eunit and txm headers
-include_lib("eunit/include/eunit.hrl").
-include("txm.hrl").

%% Test group with setup and teardown of Mnesia.
big_test_() ->

  % Tests depend on preceding tests.
  {inorder,

   % This tuple specifies a setup fun(), teardown fun() and list of test fun().
   {setup,
    % Setup starts Mnesia and node_srv, returning pid.
    fun() ->
         mnesia:start(),
         node_srv:start_link(local)
    end,

    % Cleanup stops node_srv and Mnesia.
    fun(_) ->
         node_srv:stop(),
         mnesia:stop()
    end,

    % Test functions grouped by area.
    [basic_tests()]
    }}.


%% Returns a list of functions that test view_db functionality.
basic_tests() ->
  [
    % Checks tables are created (schema, op, folder, field and activation)
    fun() ->
         Tables = mnesia:system_info(local_tables),
         ?assertEqual(5, length(Tables)),
         ?assertEqual([schema],
                      lists:subtract(Tables, [op, field, folder, activation]))
    end,

    % Checks latency table returns test node as the closest.
    fun() ->
         ?assertEqual(node(), node_srv:closest([some, node(), nodes]))
    end,

    % Checks closest returns supplied node even if not present in table.
    fun() ->
         ?assertEqual(randomNode, node_srv:closest([randomNode]))
    end,

    % Check the ready function.
    fun() ->
         ?assertEqual(ok, node_srv:ready())
    end,

    % Checks closest throws exception if no node supplied.
    fun() ->
         ?assertException(error, _, node_srv:closest([]))
    end
   ].
